package com.zenika.training.wicket.zencontact.pages;

import org.apache.wicket.PageParameters;
import org.apache.wicket.extensions.markup.html.basic.SmartLinkLabel;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;

import com.zenika.training.wicket.zencontact.ZenContactApplication;
import com.zenika.training.wicket.zencontact.model.Contact;

public class ListContactsPage extends ZenContactBasePage {

	protected String getPageTitle() {
		return "Contacts list";
	}

	public ListContactsPage(PageParameters params) {

		final String searchString = params.getString("searchString");
		IModel contactsModel = new LoadableDetachableModel() {
			protected Object load() {
				return ZenContactApplication.getContactDao().find(searchString);
			}
		};

		ListView contacts = new ListView("contacts", contactsModel) {

			protected void populateItem(ListItem item) {

				Link view = new Link("view", item.getModel()) {
					public void onClick() {
						Contact c = (Contact) getModelObject();
						setResponsePage(new ViewContactPage(c.getId()));
					}
				};
				

				view.add(new Label("firstName", new PropertyModel(item.getModel(), "firstName")));
				view.add(new Label("lastName", new PropertyModel(item.getModel(), "lastName")));
				item.add(view);

				item.add(new SmartLinkLabel("email", new PropertyModel(item.getModel(), "email")));
				item.add(new Link("edit", item.getModel()) {
					public void onClick() {
						Contact c = (Contact) getModelObject();
						setResponsePage(new EditContactPage(c.getId()));
					}
				});
				item.add(new Link("delete", item.getModel()) {
					public void onClick() {
						Contact c = (Contact) getModelObject();
						ZenContactApplication.getContactDao().delete(c.getId());
						setResponsePage(ListContactsPage.class);
					}
				});
			}
		};
		add(contacts);
	}

}
